﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;


namespace WebSite.Web.SessionAndFilter
{
    public class AuthorAttribute : FilterAttribute, IAuthorizationFilter
    {

        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (Sessions.User == null)
            {
                Uri uri = filterContext.HttpContext.Request.Url;
                if (!uri.AbsolutePath.Equals("/Home/Login") &&!uri.AbsolutePath.Equals("/Home/LoginData") && !uri.AbsolutePath.Equals("/Home/RandomCode") && !uri.AbsolutePath.Equals("/"))
                {
                    UriBuilder uribud = new UriBuilder()
                    {
                        Host = uri.Host,
                        Path = "/Home/Login",
                        Port = uri.Port,
                        Fragment = uri.Fragment,
                        Scheme = uri.Scheme
                    };


                    //跳转到登录页面
                    if (filterContext.HttpContext.Request.IsAjaxRequest())
                    {
                        filterContext.Result = new JsonResult
                        {
                            Data = new
                            {
                                Error = "NotAuthorized",
                                LogOnUrl = uribud.Uri.ToString()
                            },
                            JsonRequestBehavior = JsonRequestBehavior.AllowGet
                        };
                    }
                    else
                    {
                        filterContext.HttpContext.Response.Write("<script type='text/javascript'>top.window.location.href='" + uribud.Uri.ToString() + "'</script>");
                        filterContext.HttpContext.Response.End();
                        filterContext.Result = new EmptyResult();
                    }
                }
                return;
            }
        }
    }
}